{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# **实验十一 图的遍历操作**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- # %%html -->\n",
    "<img src=\"实验十.png\" width=\"70%\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "class Graph(object):\n",
    "    def __init__(self, graph_dict=None):\n",
    "        if graph_dict is None:\n",
    "            graph_dict = {}\n",
    "        self.graph_dict = graph_dict\n",
    "\n",
    "    def getVertices(self):\n",
    "        '''\n",
    "        得到图的所有顶点\n",
    "        '''\n",
    "        return list(self.graph_dict.keys())\n",
    "\n",
    "    def addVertex(self, vertex):\n",
    "        '''\n",
    "        添加一个顶点\n",
    "        '''\n",
    "        if vertex not in self.graph_dict:\n",
    "            self.graph_dict[vertex] = {}\n",
    "\n",
    "    def addEdge(self, edge):\n",
    "        '''\n",
    "        添加一个边\n",
    "        (b,a) a->b的边\n",
    "        '''\n",
    "        edge = set(edge)\n",
    "        (vertex1, vertex2) = tuple(edge)\n",
    "        if vertex1 in self.graph_dict:\n",
    "            self.graph_dict[vertex1].add(vertex2)\n",
    "        else:\n",
    "            self.graph_dict[vertex1] = {vertex2, }\n",
    "\n",
    "    def findEdge(self):\n",
    "        '''\n",
    "        打印所有的边\n",
    "        '''\n",
    "        edgename = []\n",
    "        for vertex in self.graph_dict:\n",
    "            for nxtvertex in self.graph_dict[vertex]:\n",
    "                if {nxtvertex, vertex} not in edgename:\n",
    "                    edgename.append({vertex, nxtvertex})\n",
    "        return edgename\n",
    "\n",
    "#DFS指的是深度优先搜索    回溯法(会回看前面的节点)\n",
    "#一直往前走，走不下去往回跳\n",
    "#使用stack来进行深度的顺序\n",
    "#把栈顶元素去除，在把临接点放入\n",
    "def DFS(graph,s):#图  s指的是开始结点\n",
    "    #需要一个栈\n",
    "    stack=[]\n",
    "    stack.append(s)\n",
    "    seen=set()#看是否访问过\n",
    "    seen.add(s)\n",
    "    while (len(stack)>0):\n",
    "        #拿出邻接点\n",
    "        vertex=stack.pop()#这里pop参数没有0了，最后一个元素\n",
    "        nodes=graph[vertex]\n",
    "        for w in nodes:\n",
    "            if w not in seen:#如何判断是否访问过，使用一个数组\n",
    "                stack.append(w)\n",
    "                seen.add(w)\n",
    "        print(vertex)\n",
    "\n",
    "#BFS 广度优先搜索   层序遍历\n",
    "def BFS(graph,s):#graph图  s指的是开始结点\n",
    "    #需要一个队列\n",
    "    queue=[]\n",
    "    queue.append(s)\n",
    "    seen=set()#看是否访问过该结点\n",
    "    seen.add(s)\n",
    "    while (len(queue)>0):\n",
    "        vertex=queue.pop(0)#保存第一结点，并弹出，方便把他下面的子节点接入\n",
    "        nodes=graph[vertex]#子节点的数组\n",
    "        for w in nodes:\n",
    "            if w not in seen:#判断是否访问过，使用一个数组\n",
    "                queue.append(w)\n",
    "                seen.add(w)\n",
    "        print(vertex)       \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8']\n"
     ]
    }
   ],
   "source": [
    "graph_elements = {\n",
    "    'V1':['V2','V3'],\n",
    "    'V2':['V1','V4','V5'],\n",
    "    'V3':['V1','V6','V7'],\n",
    "    'V4':['V2','V8'],\n",
    "    'V5':['V2','V8'],\n",
    "    'V6':['V3','V8'],\n",
    "    'V7':['V3','V8'],\n",
    "    'V8':['V4','V5','V6','V7']\n",
    "}\n",
    "\n",
    "g = Graph(graph_elements)\n",
    "print(g.getVertices())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'V1', 'V2'},\n",
       " {'V1', 'V3'},\n",
       " {'V2', 'V4'},\n",
       " {'V2', 'V5'},\n",
       " {'V3', 'V6'},\n",
       " {'V3', 'V7'},\n",
       " {'V4', 'V8'},\n",
       " {'V5', 'V8'},\n",
       " {'V6', 'V8'},\n",
       " {'V7', 'V8'}]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 所有边\n",
    "g.findEdge()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "V1\n",
      "V3\n",
      "V7\n",
      "V8\n",
      "V5\n",
      "V4\n",
      "V6\n",
      "V2\n"
     ]
    }
   ],
   "source": [
    "# 深度优先遍历\n",
    "DFS(graph_elements,'V1')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "V1\n",
      "V2\n",
      "V3\n",
      "V4\n",
      "V5\n",
      "V6\n",
      "V7\n",
      "V8\n"
     ]
    }
   ],
   "source": [
    "# 广度优先遍历\n",
    "BFS(graph_elements,'V1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# **实验十一 图的最小生成树算法**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- # %%html -->\n",
    "<img src=\"实验十一.png\" width=\"70%\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "#coding=utf-8\n",
    "class Graph(object):\n",
    "    def __init__(self, maps):\n",
    "        self.maps = maps\n",
    "        self.nodenum = self.get_nodenum()\n",
    "        self.edgenum = self.get_edgenum()\n",
    " \n",
    "    def get_nodenum(self):\n",
    "        return len(self.maps)\n",
    " \n",
    "    def get_edgenum(self):\n",
    "        count = 0\n",
    "        for i in range(self.nodenum):\n",
    "            for j in range(i):\n",
    "                if self.maps[i][j] > 0 and self.maps[i][j] < 9999:\n",
    "                    count += 1\n",
    "        return count\n",
    " \n",
    "    def kruskal(self):\n",
    "        res = []\n",
    "        if self.nodenum <= 0 or self.edgenum < self.nodenum-1:\n",
    "            return res\n",
    "        edge_list = []\n",
    "        for i in range(self.nodenum):\n",
    "            for j in range(i,self.nodenum):\n",
    "                if self.maps[i][j] < 9999:\n",
    "                    edge_list.append([i, j, self.maps[i][j]])#按[begin, end, weight]形式加入\n",
    "        edge_list.sort(key=lambda a:a[2])#已经排好序的边集合\n",
    "        \n",
    "        group = [[i] for i in range(self.nodenum)]\n",
    "        for edge in edge_list:\n",
    "            for i in range(len(group)):\n",
    "                if edge[0] in group[i]:\n",
    "                    m = i\n",
    "                if edge[1] in group[i]:\n",
    "                    n = i\n",
    "            if m != n:\n",
    "                res.append(edge)\n",
    "                group[m] = group[m] + group[n]\n",
    "                group[n] = []\n",
    "        return res\n",
    " \n",
    "    def prim(self):\n",
    "        res = []\n",
    "        if self.nodenum <= 0 or self.edgenum < self.nodenum-1:\n",
    "            return res\n",
    "        res = []\n",
    "        seleted_node = [0]\n",
    "        candidate_node = [i for i in range(1, self.nodenum)]\n",
    "        \n",
    "        while len(candidate_node) > 0:\n",
    "            begin, end, minweight = 0, 0, 9999\n",
    "            for i in seleted_node:\n",
    "                for j in candidate_node:\n",
    "                    if self.maps[i][j] < minweight:\n",
    "                        minweight = self.maps[i][j]\n",
    "                        begin = i\n",
    "                        end = j\n",
    "            res.append([begin, end, minweight])\n",
    "            seleted_node.append(end)\n",
    "            candidate_node.remove(end)\n",
    "        return res\n",
    " \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "邻接矩阵为\n",
      "[[0, 7, 9999, 9999, 9999, 5], [7, 0, 9, 9999, 3, 9999], [9999, 9, 0, 6, 9999, 9999], [9999, 9999, 6, 0, 8, 10], [9999, 3, 9999, 8, 0, 4], [5, 9999, 9999, 10, 4, 0]]\n",
      "节点数据为6，边数为8\n",
      "\n"
     ]
    }
   ],
   "source": [
    "max_value = 9999\n",
    "row0 = [0,7,max_value,max_value,max_value,5]\n",
    "row1 = [7,0,9,max_value,3,max_value]\n",
    "row2 = [max_value,9,0,6,max_value,max_value]\n",
    "row3 = [max_value,max_value,6,0,8,10]\n",
    "row4 = [max_value,3,max_value,8,0,4]\n",
    "row5 = [5,max_value,max_value,10,4,0]\n",
    "maps = [row0, row1, row2,row3, row4, row5]\n",
    "graph = Graph(maps)\n",
    "print('邻接矩阵为\\n%s'%graph.maps)\n",
    "print('节点数据为%d，边数为%d\\n'%(graph.nodenum, graph.edgenum))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------最小生成树kruskal算法------\n",
      "[[1, 4, 3], [4, 5, 4], [0, 5, 5], [2, 3, 6], [3, 4, 8]]\n",
      "------最小生成树prim算法\n",
      "[[0, 5, 5], [5, 4, 4], [4, 1, 3], [4, 3, 8], [3, 2, 6]]\n"
     ]
    }
   ],
   "source": [
    "print('------最小生成树kruskal算法------')\n",
    "print(graph.kruskal())\n",
    "print('------最小生成树prim算法')\n",
    "print(graph.prim())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
